package dataStructure;

public class Stack {
    Node head;
    int length;

    public Stack(){
        head = null;
        length = 0;
    }


    /**
     * 压栈操作
     * @param item
     */
    public void push(int item){
        //创建一个节点
        Node newNode = new Node(item);
        Node temp = head;
        if(temp == null){
            head = newNode;
        } else {
            while(temp.next != null){
                temp = temp.next;
            }
            temp.next = newNode;
        }
        length ++ ;
    }

    /**
     * 弹栈操作
     * @return
     */
    public Integer pop(){
        Node pre = head;
        Node after = null;
        if(head == null){
            return null;
        } else {
            while(pre.next != null){
                after = pre;
                pre = pre.next;
            }
            int item = pre.item;
            after.next = null;
            length --;
            return item;
        }
    }

    /**
     * 获取栈顶元素
     * @return
     */
    public Integer peak(){
        Node temp = head;
        if(temp == null){
            return null;
        } else {
            while(temp.next != null){
                temp = temp.next;
            }
            return temp.item;
        }
    }

    public void print(){
        Node temp = head;
        if (head == null){
            System.out.println("The stack is null");
        } else {
            while(temp != null){
                System.out.println(temp.item);
                temp = temp.next;
            }
        }
    }

    /**
     * 获取栈的深度
     * @return
     */
    public int getLength() {
        return length;
    }

}
